<template>
  <div class="page-container page-footer-btn">
    <van-cell-group>
      <van-field is-link @click="showPopup" placeholder="请选择仓库" label="仓库" :value="form.warehouseName"></van-field>
      <van-popup v-model="show" position="right" class="popup">
        <van-search v-model="form.warehouseName" placeholder="请输入关键词" shape="round"  background="#1989fa" @input="whfilter" />
        <van-checkbox-group>
          <van-cell-group>
            <van-cell
              v-for="(item, index) in searchedList"
              clickable
              :key="item.warehouseId"
              :title="item.warehouseName"
              @click="deptCheck(item, index)"
            >
            </van-cell>
          </van-cell-group>
        </van-checkbox-group>
      </van-popup>

      <FortenScan
        ref="scanDom"
        propPlaceholder="请扫描SN/RFID"
        propErrorMsg="请扫描正确的SN/RFID"
        :propTypeArr="['sn','rfid']"
        @scanCall="handleScanOver"
      />

      <van-field label="科室名称:" label-align="left" v-model="form.deptName" size="mini" disabled/>
      <van-field v-if="form.id" label="消耗单号:" label-align="left" v-model="form.useKey" size="mini" disabled />
      <van-field v-if="form.id" label="金额:" label-align="left" v-model="form.amount" size="mini" disabled />
    </van-cell-group>
    <van-divider><span style="font-size:9px">科室消耗单冲红明细</span></van-divider>
    <div class="items-container">
      <DeptUseRedItem
        style="margin-top:5px;"
        v-for="item in formItems"
        :key="item.id"
        :value="item"
        v-on:delete="deleteItem(item)"
      />
    </div>
      <van-row  class="footer-btn" type="flex" justify="space-around">
        <van-col span="12">
          <flow-buttons
            :propFlowKey="propFlowKey"
            @button-click="handleFlowButtonClick"
          />
        </van-col>
        <van-col span="6">
          <van-button text="创建"   type="primary" @click="handleCreate"></van-button>
        </van-col>
      </van-row>
    </div>
</template>

<script>
/* eslint-disable*/
import { Button , Popup, Sticky, List, Image as VanImage, NumberKeyboard, DatetimePicker, Swipe, SwipeItem, RadioGroup, Radio, Checkbox, CheckboxGroup   } from 'vant'
import Vue from 'vue'
import FlowButtons from '@/components/FlowButtons.vue'
import DeptUseRedItem from './DeptUseRedItem.vue'
import barcodeParse from '@/util/barcodeParse.js'

Vue.use(Swipe)
Vue.use(SwipeItem)
Vue.use(DatetimePicker)
Vue.use(VanImage)
Vue.use(NumberKeyboard)
Vue.use(List)
Vue.use(Popup)

export default {
  data() {
    return {
      form: {},
      formItems: {},
      images: [],
      searchedList: [],
      warehouseList: [],
      result: [],
      stockIds: [],
      ids: [],
      searchValue: '',
      scan: '',
      show: false,
    }
  },
  props: {
    propFlowKey: String
  },
  mounted() {
    this.$refs.scanDom.focus()
    this.getBaseData()
  },
  computed: {
  },
  methods: {
    getBaseData(){
      this.getDept()
      this.getWarehouseList()
      this.getWarehouse()
    },
    getDept(){
      const currentUser = this.$store.getters.currentUser.currentUser
      this.$set(this.form, 'deptName', currentUser.deptName)
      this.$set(this.form, 'deptId', currentUser.deptId)
    },
    getWarehouse(){
      this.$set(this.form, 'warehouseId', this.$store.getters.currentWarehouse.warehouseId)
      this.$set(this.form, 'warehouseName', this.$store.getters.currentWarehouse.warehouseName)
    },
    getWarehouseList(){
      this.$ajax.get('/base/user_warehouse/getByCurrentUser').then(res => {
        if(res.code == 0){
          this.warehouseList = res.data || []
          this.searchedList = this.warehouseList
          this.utils.loadHide()
        }
      }).catch(err=> {
        this.utils.loadHide()
      })
    },
    deleteItem(value){
      this.ids.push(value.id)
        const params = { ids: this.ids }
        this.$ajax.delete('/dept/use_dtl/delete', {data: params}).then(resp => {
        if(resp.code == 0){
          this.$notify.success('删除成功')
          this.getDeptUse(this.form.useKey)
        } else {
          this.$notify.warning(resp.msg)
        }
      }).catch(err =>{
          this.utils.loadHide()
      })
    },
    handleScanClear(event) {
      this.scan = ''
    },
    showPopup() {
      this.show = true;
      this.utils.loadShow()
      this.getWarehouseList()
    },
    handleScanOver(scanValue) {
      let prefix = scanValue.substring(0, 2)
      let codeType = ''
      if (prefix != 'DU'){
        codeType = barcodeParse.barCodeType(scanValue)
        if (codeType != 'SN' && codeType != 'RFID') {
          window.scanError()
          this.$notify.warning('请扫描有效的条码')
          return
        }
        this.getByCode(scanValue,codeType)
      } else {
        this.getDeptUse(scanValue)
      }
      this.scan = null
    },
    getByCode(code,codeType){
      let wrapper = this.$newWrapper().eq(codeType.toLowerCase(), code)
      let params = {
        queryString: JSON.stringify(wrapper.queryConditions),
      }
      this.stockIds = []
      let flag = 0
        this.$ajax.get('/wm/stock/list', { params }).then((resp) => {
        if(resp.code == 0){
          if(resp.data && resp.data.length > 0){
            let stock = resp.data[0]
            this.stockIds.push(stock.id)
            this.saveUse()
          } else {
            this.$notify.warning('未查询到库存')
          }
        } else {
          this.$notify.warning(resp.msg)
          return
        }
      }).catch(err =>{
        this.utils.loadHide()
        return
      })
    },
    saveUse() {
      this.utils.loadShow()
      if(!this.form.id){
        this.saveDeptUse()
      } else {
        this.saveUseItem()
      }
    },
    saveDeptUse(){
      const params = {
        useDate: new Date().format('yyyy-MM-dd'),
        flagUseRedType: 1,
        useType: "MANUAL",
        deptId: this.form.deptId,
        warehouseId: this.form.warehouseId,
        warehouseName: this.form.warehouseName
      }
      this.$ajax.post('/dept/use/save', params).then(res => {
        if(res.code == 0){
          this.form = res.data
          this.saveUseItem()
        }
      }).catch(err =>{
        this.utils.loadHide()
        return
      })
      this.utils.loadHide()
    },
    saveUseItem(){
      let params = {
        stockIds: this.stockIds,
        useId: this.form.id
      }
      this.$ajax.post('/dept/use_dtl/saveItemByCode', params).then((resp) => {
        if (resp.code == 0) {
          this.scan = ''
          this.stockIds = []
          this.getDeptUse(this.form.useKey)
        } else {
          this.utils.loadHide()
        }
      })
      .catch(() => {
        this.stockIds = []
        this.utils.loadHide()
      })
    },
    getDeptUse(code){
      const params = {
        code: code
      }
      this.utils.loadShow()
      this.$ajax.get('/dept/use/getDeptUse', { params }).then(response => {
        this.utils.loadHide()
        if(response.code ==0){
          this.form = response.data.use || []
          this.formItems = response.data.useItems || []
        } else {
            this.$notify.error(response.msg)
          return
        }
      }).catch(err => {
        this.utils.loadHide()
      })
    },
    async handleFlowButtonClick(button) {
      if (!this.form.id) {
        this.$notify.warning('你还没创建单据！')
        return
      }
      const result = await this.$dialog.confirm({
        title: '流程确认',
        message: `确定要进行${button.title}操作吗？`
      });
      if (!result) return;

      this.utils.loadShow()
      let busId = '';
      busId = this.form.id
      const flowKey = this.propFlowKey.split(':')[0];
      let params = {
        flowKey,
        buttonKey: button.code,
        busId: this.form.id
      };
      this.$ajax.post('/dept/use/flow_change', params).then(response => {
        this.utils.loadHide()
        if (response.code === 0) {
          this.$notify.success(`${button.title}操作成功！`);
          this.clearForm()
        }
      }).catch(err => {
        this.utils.loadHide()
      })
    },
    clearForm() {
      this.form = {};
      this.formItems = [];
      this.scan = '';
      this.$refs.scanDom.focus()
      this.getBaseData()
    },
    whfilter() {
      this.searchedList = this.warehouseList.filter(item => item.warehouseName.indexOf(this.form.warehouseName) > -1
        || this.pyutils.chineseToPinYin(item.warehouseName).indexOf(this.form.warehouseName) > -1)
    },
    deptCheck(item, index){
      if (this.form.warehouseId == item.warehouseId) {
        this.show = false
        return
      }
      this.reCheck(item)
    },
    reCheck(item){
      this.clearForm()
      this.getDept()
      this.$set(this.form, 'warehouseId' , item.warehouseId)
      this.$set(this.form, 'warehouseName' , item.warehouseName)
      this.show = false
    },
    handleCreate(){
      if (this.form.id) {
        this.$dialog.confirm({
          message: '当前单据未提交，是否创建新单据?',
        }).then(() => {
          this.clearForm()
          this.getBaseData()
        }).catch(() => {
          // on cancel
        })
      }
    }
  },
  components: {
    DeptUseRedItem,
    FlowButtons,
    RadioGroup,
    Sticky,
    Checkbox,
    CheckboxGroup,
    Radio,
    Button
  }

}
</script>

<style lang="scss" scoped>
  .items-container {
    min-height: 80px;
  }
  .popup {
    width: 80%;
    height: 100%;
  }
  .footer{
    position: fixed;
    left: 0px;
    bottom: 0px;
    width: 100%;
    height: 50px;
  }
  .btn-container {
    margin-left: 1%;
    margin-right: 1%;
    flex-direction:column ;
    justify-content: space-between;
    display:inline-block;
    width: 80%;
  }
  .creat{
    margin-left: 1%;
    flex-direction:column ;
    justify-content: space-between;
  }
</style>
